import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;

public class JAPI_SocketInputStream extends DataInputStream {
	private InputStream is;

	private byte[] recvbuf = new byte[4];
	private char[] lineBuffer;

	public JAPI_SocketInputStream(InputStream ins) {
		super(ins);
		is = ins;
	}

	public void recv(byte[] b, int len) throws IOException {
		int readn = 0, part = 0;

		while (len > 0) {
			part = is.read(b, readn, len);

			if (part > 0) {
				readn += part;
				len -= part;
			}
			if (part == -1) {
				for (part = 0; part < len; part++)
					b[part] = 0;
				return;
			}

			// System.err.println("Gelesen "+part);
		}
	}

	public int recvInt() throws IOException {
		int val = 0;

		recv(recvbuf, 4);

		val = ((char) recvbuf[3] & 0xff);
		val = (val << 8) | ((char) recvbuf[2] & 0xff);
		val = (val << 8) | ((char) recvbuf[1] & 0xff);
		val = (val << 8) | ((char) recvbuf[0] & 0xff);

		return (val);
	}

	public String jsiReadLine() throws IOException {
		char buf[] = lineBuffer;

		if (buf == null) {
			buf = lineBuffer = new char[128];
		}

		int room = buf.length;
		int offset = 0;
		int c;

		loop: while (true) {
			switch (c = is.read()) {
			case -1:
			case '\n':
				break loop;

			case '\r':
				int c2 = is.read();
				if ((c2 != '\n') && (c2 != -1)) {
					if (!(is instanceof PushbackInputStream)) {
						this.is = new PushbackInputStream(in);
					}
					((PushbackInputStream) is).unread(c2);
				}
				break loop;

			default:
				if (--room < 0) {
					buf = new char[offset + 128];
					room = buf.length - offset - 1;
					System.arraycopy(lineBuffer, 0, buf, 0, offset);
					lineBuffer = buf;
				}
				buf[offset++] = (char) c;
				break;
			}
		}
		if ((c == -1) && (offset == 0)) {
			return null;
		}
		return String.copyValueOf(buf, 0, offset);
	}
}
